import axios from 'axios';
import { Message } from 'element-ui';
import router from '../router';

const request = axios.create({
  baseURL: process.env.VUE_APP_API,
  withCredentials: false,
  timeout: 120000,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
  },
});

// request拦截器
request.interceptors.request.use(
  (config) => {
    const Authorization = sessionStorage.getItem('token');
    if (Authorization) {
      config.headers['Authorization'] = `${Authorization}`;
    }

    return config;
  },
  (error) => {
    // Do something with request error
    Promise.reject(error);
  },
);

// response 拦截器
request.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      // return Promise.resolve(response);
      const res = response.data;
      // if (res.code === 3) {
      //   sessionStorage.removeItem('Authorization');
      //   router.push('/login');
      // }
      return res;
    }
    return Promise.reject(response);
  },
  // eslint-disable-next-line consistent-return
  (error) => {
    let data;
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          // 未登录
          sessionStorage.removeItem('token');
          router.push('/login');
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        case 403:
          sessionStorage.removeItem('token');
          router.push('/login');
          Message({
            showClose: true,
            message: error.response.data.message || '客户端错误',
            type: 'error',
            duration: 1000,
          });
          break;
        case 404:
          Message({
            showClose: true,
            message: error.response.data || '网络请求不存在',
            type: 'error',
            duration: 1000,
          });
          break;
        // 其他错误
        default:
          Message({
            showClose: true,
            message: error.response.data.message || 'Network Error',
            type: 'error',
            duration: 1000,
          });
      }
      // return Promise.reject(error.response);
    } else {
      const message = 'Network Error';
      data = {
        showClose: true,
        message,
        status: '504',
        type: 'error',
        duration: 1500,
      };
      Message(data);
    }
    return Promise.reject(error);
  },
);

export default request;
